import asyncio
from .browser import AsyncBrowser
from pyquery import PyQuery as pq

MAX_CONCURRENCY = 24

async def main(semaphore: asyncio.Semaphore, url: str):
    # 初始化浏览器
    async with semaphore:
        retries = 3
        for attempt in range(retries):
            browser = AsyncBrowser()

            try:
                await browser.init_browser(
                    {
                        "executable_path": "resources/chrome-win/chrome.exe",
                        "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
                        "headless": True,
                        "proxy": None,
                        "args": [
                            "--lang=en-US", 
                            "--blink-settings=imagesEnabled=false",
                            "--disable-extensions",
                            "--disable-gpu",
                            "--disable-software-rasterizer"
                        ]
                    }
                )
                # 打开网页
                await browser.page.goto(url, timeout=100000)
                # 获取页面内容
                # await asyncio.sleep(50)
                doc = pq(await browser.page.content())
                # 打印页面标题
                print(doc("title").text())
                return { 
                    "status": "success", 
                    "data": doc("title").text() 
                }
            except Exception as e:
                print(f"Attempt {attempt + 1} failed: {e}")
                if attempt == retries - 1:
                    return { 
                        "status": "error", 
                        "data": str(e) 
                    }
                await asyncio.sleep(5)  # 等待 5 秒后重试
            finally:
                # 关闭浏览器
                await browser.close()

def run(url: str):
    semaphore = asyncio.Semaphore(MAX_CONCURRENCY)
    result = asyncio.run(main(semaphore, url))
    return result
